package com.bnlr.lrparking.appui.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bnlr.lrparking.appui.stall.StallDetailsActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.HorizontalAdapter;
import com.bnlr.lrparking.adapter.SearchStallAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.StallData;
import com.bnlr.lrparking.model.StallM;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class SearchStallActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.lv_search_list)
    RecyclerView recyclerView;
    @BindView(R.id.complain_scrollIndicatorView)
    ScrollIndicatorView scrollIndicatorView;
    @BindView(R.id.synth_sort)
    RelativeLayout synth_sort;
    @BindView(R.id.price_sort)
    RelativeLayout price_sort;
    @BindView(R.id.earnings_sort)
    RelativeLayout earnings_sort;
    @BindView(R.id.no_data)
    RelativeLayout no_data;
    @BindView(R.id.tv_synth)
    TextView tv_synth;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_earnings)
    TextView tv_earnings;
    @BindView(R.id.et_title_search)
    EditText etTitleSearch;
    @BindView(R.id.img_deleteall)
    ImageView ivClose;
    private SearchStallAdapter mAdapter;
    private List<StallData> mList = new ArrayList<>();
    private List<String> catoryList = new ArrayList<>();
    private int ownerType = 0;//车位所属
    private int orderBy = 0;//车位排序
    private int currentPage = 1;
    private String keyWords = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_stall);
        unbinder = ButterKnife.bind(this);
        initView();

    }

    private void initView() {
        getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
        catoryList.add("平台车位");
        catoryList.add("个人车位");
        catoryList.add("开发车位");
        catoryList.add("其他车位");
        catoryList.add("收藏车位");
        set(scrollIndicatorView, catoryList);
        tv_synth.setTextColor(this.getResources().getColor(R.color.main_color));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter =new SearchStallAdapter(mList);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                //  上拉加载
                currentPage++;
                getListData(ownerType, orderBy,currentPage,keyWords,"load");
            }
        },recyclerView);

        recyclerView.setAdapter(mAdapter);
        etTitleSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是 "DONE" 键*/
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive())
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    if (!TextUtils.isEmpty(etTitleSearch.getText().toString())) {
                        keyWords = etTitleSearch.getText().toString();
                        currentPage = 1;
                        getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                    } else {
                        CommonUtil.showToask(baseContext, "请输入您要搜索的内容");
                    }
                    return true;
                }
                return false;
            }
        });
        etTitleSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWords = s.toString();
                if (!s.toString().equals("")){
                    ivClose.setVisibility(View.VISIBLE);
                }else {
                    ivClose.setVisibility(View.GONE);
                }
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int i) {
                Intent intent = new Intent(SearchStallActivity.this, StallDetailsActivity.class);
                intent.putExtra("monthCount",mList.get(i).getMonthCount());//最大投资时间
                intent.putExtra("id", mList.get(i).getId());
                intent.putExtra("number", mList.get(i).getNumber());
                intent.putExtra("type", mList.get(i).getParkSpaceType());//类型
                intent.putExtra("size", mList.get(i).getArea());//大小
                intent.putExtra("their", mList.get(i).getOwnerType());
                intent.putExtra("incomerockon", mList.get(i).getIncomeRockon());//收益值
                intent.putExtra("sellingprice", mList.get(i).getSellingPrice());//共享值
                intent.putExtra("time", mList.get(i).getBeginTime());
                intent.putExtra("time1", mList.get(i).getEndTime());
                intent.putExtra("address", mList.get(i).getAddress());
                intent.putExtra("parkphoto",mList.get(i).getParkPhoto());
                intent.putExtra("IsFavorite", mList.get(i).getIsFavorite());
                startActivity(intent);
            }
        });
    }

    /**
     * 配置导航

     */
    private void set(final Indicator indicator, List list) {
        int selectColor = getResources().getColor(R.color.main_color);
        int unSelectColor = getResources().getColor(R.color.text_color);
        indicator.setAdapter(new HorizontalAdapter(this, list));
        indicator.setScrollBar(new ColorBar(getApplicationContext(), selectColor, 6));
        float unSelectSize = 13;
        float selectSize = unSelectSize * 1f;
        indicator.getItemView(1).setMinimumWidth(30);
        indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor).setSize(selectSize, unSelectSize));
        indicator.setItemClickable(true);

        indicator.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                if (select == 0) {
                    ownerType = 0;
                } else if (select == 1) {
                    ownerType = 1;
                } else if (select == 2) {
                    ownerType = 2;
                } else if (select == 3) {
                    ownerType = 3;
                } else if (select == 4) {
                    ownerType = 4;
                }
                if (mAdapter != null) {
                    currentPage = 1;
                    getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                }
            }
        });
    }
    @OnClick({R.id.synth_sort,R.id.price_sort,R.id.earnings_sort,R.id.rely_search_back,R.id.img_deleteall})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rely_search_back:
                finish();
                break;
            case R.id.synth_sort:
                orderBy = 0;
                tv_synth.setTextColor(this.getResources().getColor(R.color.main_color));
                tv_price.setTextColor(this.getResources().getColor(R.color.gray03_color));
                tv_earnings.setTextColor(this.getResources().getColor(R.color.gray03_color));
                if (mAdapter != null) {
                    currentPage = 1;
                    getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                }
                break;
            case R.id.price_sort:
                orderBy = 1;
                tv_synth.setTextColor(this.getResources().getColor(R.color.gray03_color));
                tv_price.setTextColor(this.getResources().getColor(R.color.main_color));
                tv_earnings.setTextColor(this.getResources().getColor(R.color.gray03_color));
                if (mAdapter != null) {
                    currentPage = 1;
                    getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                }
                break;
            case R.id.earnings_sort:
                orderBy = 2;
                tv_synth.setTextColor(this.getResources().getColor(R.color.gray03_color));
                tv_price.setTextColor(this.getResources().getColor(R.color.gray03_color));
                tv_earnings.setTextColor(this.getResources().getColor(R.color.main_color));
                if (mAdapter != null) {
                    currentPage = 1;
                    getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                }
                break;
            case R.id.img_deleteall:
                keyWords = "";
                etTitleSearch.setText("");
                currentPage = 1;
                getListData(ownerType, orderBy,currentPage,keyWords,"refresh");
                break;
        }

    }

    private void getListData(int ownerType, int orderBy, int page, String keyWords, final String handTag) {
        try {
            if (CommonUtil.isNetworkAvailable(this) == 0) {
                CommonUtil.showToask(this, "当前无网络连接，请检查网络设置");
                return;
            }
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetVitrualParkSpaceList");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("lng", Params.CurrentLon);
            mRequest.add("lat", Params.CurrentLat);
            mRequest.add("ownerType", ownerType);//车位类型0-4
            mRequest.add("orderBy", orderBy);//排序1-3
            mRequest.add("pageIndex", page);//
            mRequest.add("keyWords", keyWords);
            Log.e("虚拟车位：", AppConfig.getInstance().getString("uid", ""));
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<StallM>(this, true, StallM.class) {
                        @Override
                        public void doWork(StallM data, String code) {
                            if ("1".equals(code)) {
                                if (mAdapter != null) {
                                    if (data != null && data.getData().size() != 0) {
                                        if (handTag.equals("refresh")) {
                                            no_data.setVisibility(View.GONE);
                                            mList = data.getData();
                                            mAdapter.setNewData(data.getData());
                                        } else {
                                            mList.addAll(data.getData());
                                            mAdapter.notifyDataSetChanged();
                                        }
                                        mAdapter.loadMoreComplete();
                                    } else {
                                        if (handTag.equals("refresh")) {
                                            no_data.setVisibility(View.VISIBLE);
                                        } else {
                                            mAdapter.loadMoreEnd();
                                        }
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("0".equals(code)) {

                                    if (mAdapter != null) {
                                        if (handTag.equals("refresh")) {
                                            mList.clear();
                                            mAdapter.notifyDataSetChanged();
                                            no_data.setVisibility(View.VISIBLE);
                                        } else {
                                            mAdapter.loadMoreEnd();
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
